package com.lw.leetcode.str.b;

/**
 * Created with IntelliJ IDEA.
 * 1616. 分割两个字符串得到回文串
 *
 * @author liw
 * @version 1.0
 * @date 2022/5/27 9:17
 */
public class CheckPalindromeFormation {

    public static void main(String[] args) {
        CheckPalindromeFormation test = new CheckPalindromeFormation();

        // true
//        String a = "abdef";
//        String b = "fecab";

        // true
//        String a = "ulacfd";
//        String b = "jizalu";

        // true
//        String a = "x";
//        String b = "y";

        // true
        String a = "ab";
        String b = "cd";

        boolean b1 = test.checkPalindromeFormation(a, b);
        System.out.println(b1);
    }

    public boolean checkPalindromeFormation(String a, String b) {
        int length = a.length();
        char[] as = a.toCharArray();
        char[] bs = b.toCharArray();
        int i = (length - 1) >> 1;
        int j = length >> 1;
        return find(as, bs, i, j) || find(bs, as, i, j);
    }

    private boolean find(char[] as, char[] bs, int i, int j) {
        while (i >= 0) {
            if (as[i] == as[j]) {
                i--;
                j++;
            } else {
                break;
            }
        }
        if (i < 0) {
            return true;
        }
        int m = i;
        int n = j;
        while (i >= 0) {
            if (bs[i] == as[j]) {
                i--;
                j++;
            } else {
                break;
            }
        }
        if (i < 0) {
            return true;
        }
        i = m;
        j = n;
        while (i >= 0) {
            if (as[i] == bs[j]) {
                i--;
                j++;
            } else {
                break;
            }
        }
        return i < 0;
    }

}
